package com.action;

import com.dao.mapper.StudentMapper;
import com.model.Student;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import com.service.RandomStudent;

/*
* 编程式事务管理
* 使用spring TransactionTemplate模板*
* */
@Component
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:springmybatis.xml"})
public class TxTransactionTemplate {

//    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:springmybatis.xml");
//    StudentMapper studentMapper = (StudentMapper) applicationContext.getBean("studentMapper");
//    TransactionTemplate transactionTemplate = (TransactionTemplate)applicationContext.getBean("transactionTemplate");

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    TransactionTemplate transactionTemplate;


    Student student = new RandomStudent().getStudent();

    @Test
    public void curdTest(){

        //重写execute方法实现事务管理
        transactionTemplate.execute(new TransactionCallbackWithoutResult(){

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                studentMapper.insertOne(student);
//                int i = 1/0;
                studentMapper.insertOne(student);
            }
        });

    }
}
